//
//  SEGViewController.m
//  SEGWebView
//
//  Created by samlau7245@icloud.com on 03/05/2020.
//  Copyright (c) 2020 samlau7245@icloud.com. All rights reserved.
//
#import <SVProgressHUD.h>

#import "SEGViewController.h"
#import <SEGWKWebViewController.h>
#import <NSString+WKAdd.h>

#if __has_include(<Commom/CommomHeader.h>)
#import <Commom/CommomHeader.h>
#else
#import "CommomHeader.h"
#endif
#import "SEGWebViewController.h"
#import "SEGProfileModel.h"

@interface SEGViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)UITextField *textField;
@property (nonatomic, strong)UIButton *confirmButton;
@property (nonatomic, strong)UIButton *loginButton;
@property (nonatomic, strong)UIButton *menuButton;
@property (nonatomic, strong)UIButton *logoutButton;
@property (nonatomic, strong)UIButton *payButton;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong) NSMutableArray<NSDictionary *> *dataSource;
@property (nonatomic, strong)UIScrollView *scrollView;
@end

@implementation SEGViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    
    _scrollView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:self.scrollView];
    
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(15, 100, [UIScreen mainScreen].bounds.size.width-30, 44)];
    _textField.backgroundColor = [UIColor grayColor];
    [_textField becomeFirstResponder];
    _textField.layer.masksToBounds = YES;
    _textField.layer.cornerRadius = 5;
    [self.scrollView addSubview:_textField];
    
    _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_confirmButton addTarget:self action:@selector(confirmClick) forControlEvents:UIControlEventTouchUpInside];
    [_confirmButton setTitle:@"跳转" forState:UIControlStateNormal];
    [_confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_confirmButton setBackgroundColor:[UIColor redColor]];
    [_confirmButton sizeToFit];
    _confirmButton.frame = CGRectMake(15,CGRectGetMaxY(_textField.frame)+10, [UIScreen mainScreen].bounds.size.width-30, CGRectGetHeight(_confirmButton.bounds));
    _confirmButton.layer.masksToBounds = YES;
    _confirmButton.layer.cornerRadius = 5;
    [self.scrollView addSubview:_confirmButton];
    
    _loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_loginButton addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    [_loginButton setTitle:@"Login" forState:UIControlStateNormal];
    [_loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_loginButton setBackgroundColor:[UIColor redColor]];
    [_loginButton sizeToFit];
    _loginButton.frame = CGRectMake(15,CGRectGetMaxY(_confirmButton.frame)+10, [UIScreen mainScreen].bounds.size.width-30, CGRectGetHeight(_confirmButton.bounds));
    _loginButton.layer.masksToBounds = YES;
    _loginButton.layer.cornerRadius = 5;
    [self.scrollView addSubview:_loginButton];
    
    _menuButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_menuButton addTarget:self action:@selector(menu) forControlEvents:UIControlEventTouchUpInside];
    [_menuButton setTitle:@"拉取测试URL" forState:UIControlStateNormal];
    [_menuButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_menuButton setBackgroundColor:[UIColor redColor]];
    [_menuButton sizeToFit];
    _menuButton.frame = CGRectMake(15,CGRectGetMaxY(_loginButton.frame)+10, [UIScreen mainScreen].bounds.size.width-30, CGRectGetHeight(_menuButton.bounds));
    _menuButton.layer.masksToBounds = YES;
    _menuButton.layer.cornerRadius = 5;
    [self.scrollView addSubview:_menuButton];
    
    _logoutButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_logoutButton addTarget:self action:@selector(Logout) forControlEvents:UIControlEventTouchUpInside];
    [_logoutButton setTitle:@"RemoveCookies" forState:UIControlStateNormal];
    [_logoutButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_logoutButton setBackgroundColor:[UIColor redColor]];
    [_logoutButton sizeToFit];
    _logoutButton.frame = CGRectMake(15,CGRectGetMaxY(_menuButton.frame)+10, [UIScreen mainScreen].bounds.size.width-30, CGRectGetHeight(_confirmButton.bounds));
    _logoutButton.layer.masksToBounds = YES;
    _logoutButton.layer.cornerRadius = 5;
    [self.scrollView addSubview:_logoutButton];
    
    _payButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_payButton addTarget:self action:@selector(pay) forControlEvents:UIControlEventTouchUpInside];
    [_payButton setTitle:@"发起支付" forState:UIControlStateNormal];
    [_payButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_payButton setBackgroundColor:[UIColor redColor]];
    [_payButton sizeToFit];
    _payButton.frame = CGRectMake(15,CGRectGetMaxY(_logoutButton.frame)+10, [UIScreen mainScreen].bounds.size.width-30, CGRectGetHeight(_confirmButton.bounds));
    _payButton.layer.masksToBounds = YES;
    _payButton.layer.cornerRadius = 5;
    [self.scrollView addSubview:_payButton];
    
    _dataSource = [NSMutableArray array];
    self.tableView.frame = CGRectMake(15,CGRectGetMaxY(_payButton.frame)+10, [UIScreen mainScreen].bounds.size.width-30, 400);
    [self.scrollView addSubview:self.tableView];
    [self.tableView reloadData];
    
    self.scrollView.contentSize = CGSizeMake(CGRectGetWidth(self.scrollView.frame), CGRectGetMaxY(self.tableView.frame) + 100);
}

-(void)confirmClick{
    SEGWebViewConfig *config = [[SEGWebViewConfig alloc] init];
    config.progressColor = UIColor.orangeColor;
    SEGWebViewController *webVC = [[SEGWebViewController alloc] initWithConfig:config];
    webVC.linkURL = _textField.text.length <= 0 ? @"https://www.msnewlifefitness.com/web/test.html" : _textField.text;
    webVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webVC animated:YES];
}

-(void)login{
    NSDictionary* params = @{
        @"tel" : @"18816820401",
        @"password" : @"111111",
        @"loginType":@"1"
    };
    
    [SVProgressHUD show];
    [SEGHTTPBusinessManager seg_requestWithMethod:POST URLString:@"http://gamma.uhomecp.com/authc-restapi/v1/user/auth/login" parameters:params completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        [SVProgressHUD dismiss];
        if (isSuccessed) {
            [SVProgressHUD show];
            [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:@"http://gamma.uhomecp.com/uhomecp-sso/v3/userApp/profile" parameters:nil completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
                [SVProgressHUD dismiss];
                if (isSuccessed) {
                    NSDictionary *data =  [result valueForKey:@"data"];
                    [SEGProfileManager sharedManager].profile = [SEGProfileModel yy_modelWithJSON:data];
                    [[[UIAlertView alloc] initWithTitle:@"NOTICE" message:@"LOGIN SUCCESS" delegate:nil cancelButtonTitle:@"HIDE" otherButtonTitles:nil, nil] show];
                }
            }];
        }
    }];
}

-(void)loadMenue{
    NSDictionary* params = @{
        @"appCode" : @"SEGI",
        @"menuSid" : @"0",
        @"menuVersion":@"1",
        @"settingsId":@"0"
    };
    [self.dataSource removeAllObjects];
    [SVProgressHUD show];
    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:@"http://gamma.uhomecp.com/bms-api/menu-api/menuList2" parameters:params completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        [SVProgressHUD dismiss];
        if (isSuccessed) {
            dispatch_group_t group = dispatch_group_create();
            dispatch_queue_t queue = dispatch_queue_create("com.uhome.menu.server", DISPATCH_QUEUE_CONCURRENT);
            
            NSArray<NSDictionary*> * data = [result valueForKey:@"data"];
            [data enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                dispatch_group_async(group, queue, ^{
                    [self loadMenue:[obj valueForKey:@"menuSid"] settingsId:[obj valueForKey:@"settingsId"] group:group];
                });
            }];
            dispatch_group_notify(group, queue, ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableView reloadData];
                });
            });
        }else{
            [[[UIAlertView alloc] initWithTitle:@"NOTICE" message:@"Load Fail" delegate:nil cancelButtonTitle:@"HIDE" otherButtonTitles:nil, nil] show];
        }
    }];
    [_dataSource addObject:@{@"name":@"到家服务",@"url":@"http://gamma.uhomecp.com/h5/homeService/"}];
    [_dataSource addObject:@{@"name":@"积分商场2.0主页",@"url":@"http://gamma.uhomecp.com/h5/bonuses-h5-v2/index.html#/"}];
    [_dataSource addObject:@{@"name":@"无纸化协议",@"url":@"http://gamma.uhomecp.com/h5/agreement/index.html"}];
    [_dataSource addObject:@{@"name":@"等级",@"url":@"http://gamma.uhomecp.com/h5/bonuses-h5/index.html?router=lvcondition"}];
}

-(void)loadMenue:(NSString*)menuSid settingsId:(NSString*)settingsId group:(dispatch_group_t)group{
    NSLog(@"%@",menuSid);
    dispatch_group_enter(group);
    NSDictionary* params = @{
        @"appCode" : @"SEGI",
        @"menuSid" : menuSid,
        @"menuVersion":@"1",
        @"settingsId":settingsId
    };
    
    [SVProgressHUD show];
    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:@"http://gamma.uhomecp.com/bms-api/menu-api/menuList2" parameters:params completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        [SVProgressHUD dismiss];
        if (isSuccessed) {
            NSArray<NSDictionary*> * data = [result valueForKey:@"data"];
            [data enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj valueForKey:@"type"] && [[NSString toString:[obj valueForKey:@"type"]] isEqualToString:@"1"]) {
                    [self.dataSource addObject:@{@"name":[obj valueForKey:@"serviceName"],@"url":[obj valueForKey:@"action"]}];
                }
            }];
            dispatch_group_leave(group);
        }
    }];
}

-(void)Logout{
    [[SEGHTTPManager sharedNetworkManager] removeCookies];
    [[[UIAlertView alloc] initWithTitle:@"NOTICE" message:@"remove Cookies Success" delegate:nil cancelButtonTitle:@"HIDE" otherButtonTitles:nil, nil] show];
}

-(void)menu{
    [self loadMenue];
}

-(void)pay{
    NSURL *url = [NSURL URLWithString:@"app2Scheme://"];
    if (![[UIApplication sharedApplication] canOpenURL:url]){
        NSLog(@"没有安装应用SchemesA");
        return;
    }
    [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
    }];
}

#pragma mark - getter
- (UITableView*)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        UIView *f =  [[UIView alloc] init];
        _tableView.tableFooterView = f;
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        if(@available(iOS 11.0, *)){
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _tableView;
}

#pragma mark - UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    cell.textLabel.text = [self.dataSource[indexPath.row] valueForKey:@"name"];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SEGWebViewConfig *config = [[SEGWebViewConfig alloc] init];
    config.bottomItemsColor = UIColor.redColor;
    
    SEGWebViewController *webVC = [[SEGWebViewController alloc] initWithConfig:config];
    webVC.linkURL = [self.dataSource[indexPath.row] valueForKey:@"url"];
    webVC.title = [self.dataSource[indexPath.row] valueForKey:@"name"];
    webVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webVC animated:YES];
}

@end
